#include "nehewidget.h"
#include <QKeyEvent>

NeHeWidget::NeHeWidget(QWidget *parent, bool fs) :
    QGLWidget(parent)
{
    fullScreen = fs;

    setGeometry(0, 0, 640, 480);

    setWindowTitle("NeHe's OpenGL Framework");

    if (fullScreen) {
        showFullScreen();
    }
}

NeHeWidget::~NeHeWidget()
{

}

void NeHeWidget::initializeGL()
{
    /* 启用阴影平滑 */
    glShadeModel(GL_SMOOTH);

    /* 设置清除屏幕时所用的颜色 */
    glClearColor(0.0, 0.0, 0.0, 0.0);

    /* 设置深度缓存 */
    glClearDepth(1.0);

    /* 启用深度测试 */
    glEnable( GL_DEPTH_TEST );

    /* 设置深度测试的类型 */
    glDepthFunc( GL_LEQUAL );

    /* 透视修正 */
    glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );
}

void NeHeWidget::paintGL()
{
    /* 清楚屏幕和深度缓存 */
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    /* 重置当前的模型观察矩阵 */
    glLoadIdentity();

    glColor3f(1.0, 1.0, 1.0);
    glTranslatef( -1.5,  0.0, -6.0 );

    glBegin( GL_TRIANGLES );
    glVertex3f(  0.0,  1.0,  0.0 );
    glVertex3f( -1.0, -1.0,  0.0 );
    glVertex3f(  1.0, -1.0,  0.0 );
    glEnd();
}

void NeHeWidget::resizeGL(int width, int height)
{
    if (height) {
        height = 1;
    }

    /* 重置当前的视口(Viewport) */
    glViewport(0, 0, (GLint)width, (GLint)height);

    /* 选择投影矩阵 */
    glMatrixMode( GL_PROJECTION );

    /* 重置投影矩阵 */
    glLoadIdentity();

    /* 建立透视投影矩阵 */
    GLfloat zNear = 0.1;
    GLfloat zFar = 100.0;
    GLfloat aspect = (GLfloat)width/(GLfloat)height;
    GLfloat fH = tan(GLfloat(90.0/360.0*3.14159))*zNear;
    GLfloat fW = fH * aspect;
    glFrustum(-fW, fW, -fH, fH, zNear, zFar);

    /* 选择模型观察矩阵 */
    glMatrixMode( GL_MODELVIEW );

    /* 重置模型观察矩阵 */
    glLoadIdentity();


}

void NeHeWidget::keyPressEvent(QKeyEvent *e)
{
    switch ( e->key() )
    {
    case Qt::Key_F2:
        /* 如果按下了F2键，那么屏幕是否全屏的状态就切换一次。然后再根据需要，显示所要的全屏窗口或者普通窗口。*/
        fullScreen = !fullScreen;
        if ( fullScreen ) {
            showFullScreen();
        } else {
            showNormal();
            setGeometry( 0, 0, 640, 480 );
        }
        updateGL();
        break;
    case Qt::Key_Escape:
        /* 如果按下了Escape键，程序退出。 */
        close();
    }
}
